var util = require('../../utils/util.js');
var ajax = require('../../utils/ajax.js');
var common = require('../../utils/common.js');
var WxParse = require('../../utils/wxParse/wxParse.js');
var shopInfo = require('../../components/shopInfo/index.js');
var ShareActionSheet = require('../../components/shareActionSheet/index.js');
var MPage = require('../MPage.js');
var app = getApp();

Page(common.extendPage(MPage, {
    data: {
        winHei: 0,
        swiperHei: 0,
        curSwiperIndex: 0,
        shop: {},
        goodsId: '',
        skuList: [],
        curSkuItem: null,
        isLoginShow: false,
        isLogin: false,
        dataLoaded: false,

        //弹出浮层
        panel: {
            type: 1, //1.立即购买2.加入购物车
            isShow: false,
            aimation: {},
            opacityAnimation: {},
            height: 0,
            phone: '',
            yzm: '',
            yzmTime: 0,
        },

        //计数器
        counter: {
            number: 1,
            minusDisabled: false,
            addDisabled: false,
        },

        canPay: false,
        isCollected: false,
        cartAmount: 0,

        commentlist: [],
    },

    onShareAppMessage: function() {
        var {
            goodsName,
            shopInfoData
        } = this.data;
        var {
            goodsId,
            actId,
            actType
        } = this.options;
        var path = 'pages/goods/goods?' + 'recommend=' + app.getUserId();

        if (actId) {
            path += '&actId=' + actId + '&actType=' + (actType || 0);
        } else {
            path += '&goodsId=' + goodsId;
        }
        return {
            title: goodsName || shopInfoData.shop.shareTitle,
            path,
        }
    },

    onLoad: function(options) {
        var _self = this;

        _self.options = options = util.parseOptions(options);
        if (options.recommend) {
            app.setRecommend(options.recommend);
        }

        common.initApp({
            loginSuc: function() {
                shopInfo.init('shopInfoData', _self);
                _self.setData({
                    goodsId: options.goodsId,
                    isLogin: !!app.getUserSid(),
                    canPay: app.getCanPay(),
                    winHei: app.getWinHei(),
                    isFenxiao: app.getIsFenxiao() == 1,
                    hasFx: (app.globalData.modList || []).indexOf('1') > -1,
                    hasNavCart: !(app.config.tabBar && app.config.tabBar.hasCart == 0)
                });

                _self._initPage();
                _self._getCartAmount();
                _self.$loginSuc();

                _self._shareAs = new ShareActionSheet({
                    page: _self,
                    scope: 'shareActionSheet'
                });
            }
        });
    },

    onShow() {
        this.setData({
            isLogin: !!app.getUserSid()
        });
    },

    onLoginSuc() {
        this.setData({
            isLogin: true
        });
    },

    _showLogin() {
        this.setData({
            isLoginShow: true
        });
    },

    _showActionSheet() {
        var {
            goodsId,
            actId,
            actType
        } = this.options;
        var {
            isFenxiao
        } = this.data;
        var shareParams = {
            type: isFenxiao ? 2 : 1,
            goodsId: goodsId,
        };

        if (actId) { //活动
            if (actType == 0) { //秒杀
                shareParams.type = 5;
                shareParams.actId = actId;
            } else if (actType == 1) { //团购
                shareParams.type = 3;
                shareParams.actId = actId;
            }
        }
        this._shareAs.show(shareParams);
    },

    /**
     * 根据图片高度设置swiper高度
     */
    _swiperImgLoaded: function(evt) {
        if (this.data.swiperHei > 0) {
            return;
        }
        var self = this;
        var ratio = evt.detail.height / evt.detail.width;

        wx.getSystemInfo({
            success: function(res) {
                self.setData({
                    dataLoaded: true,
                    swiperHei: res.windowWidth * ratio
                });
            }
        });
    },

    /**
     * 请求页面数据
     */
    _initPage() {
        var $this = this;
        var options = $this.options;
        var {
            actId,
            actType,
            groupType,
        } = options;
        var ajaxUrl = '/openapi/CHome/goods_detail';
        var ajaxParams = {
            goodsId: options.goodsId
        };

        if (actId) { //活动
            ajaxParams.act_id = actId;

            if (actType == 0) { //秒杀
                ajaxUrl = '/openapi/CActivity/actInfo';
            } else if (actType == 1) { //团购
                ajaxUrl = '/openapi/CActivity/groupBuyActInfo';
            }
        }
        ajax.G(ajaxUrl, ajaxParams, function(data) {
            var d = data['result'];
            var skuJson = JSON.parse(d.skuJson);
            var actInfo = d.act_info;
            var imageUrls = [];

            $this._goodsSku = d.goodsSku;
            $this._skuJson = JSON.parse(d.skuJson);

            (d.imageUrls || []).forEach(function(url) {
                if (url) {
                    imageUrls.push(url);
                }
            });

            $this._setSkuList();
            $this._setSkuItem();

            if (d.goodsDetail) {
                WxParse.wxParse('article', 'html', d.goodsDetail, $this, 0);
            }

            if (actInfo) {
                if (actInfo.type == 0) { //秒杀
                    $this._lastTime = actInfo.state == 0 ? actInfo['begin_left_time'] : actInfo['left_time'];
                    actInfo.percent = Math.round(actInfo.sale_amount / actInfo.goods_amount * 100);
                } else if (actInfo.type == 1) { //团购
                    $this._lastTime = actInfo['left_time'];
                }
            }

            $this.setData({
                dataLoaded: true,
                actInfo: actInfo,
                groupType,
                lastTimeStr: util.getTimeBySec($this._lastTime || 0),
                goodsId: options.goodsId || d.goodsId,
                goodsImg: d.imageUrl || d.image_url,
                goodsName: d.name,
                salePrice: d.salePrice,
                saleNum: d.sold_amount,
                defaultSku: d.defaultSku,
                goodsSku: d.goodsSku,
                skuJson: JSON.parse(d.skuJson),
                imageUrls: imageUrls,
                bannerType: d.type, //0.轮播图 1.视频
                videoUrl: {
                    url: d.video_url
                },
                videoStyle: 'height: 464rpx',
                isCollected: d.isCollect,
                collectId: d.collectId,
                marketPrice: d.market_price,
                totalAmount: d.total_amount,
            });

            $this._resetCounter();

            if ($this._actTimer) {
                clearTimeout($this._actTimer);
            }
            if (actInfo && $this._lastTime > 0) {
                $this._actTimerDown();
            }

            $this._getLikeList();
            $this._getCommentList();
        });
    },

    _actTimerDown() {
        var _self = this;
        var sec = _self._lastTime;
        var lastTimeStr = util.getTimeBySec(sec, _self.options.actType == 1 ? 'd' : null);

        _self.setData({
            lastTimeStr,
        });
        if (sec == 0) {
            clearTimeout(_self._actTimer);
            _self._initPage();
            return;
        }
        _self._lastTime--;
        _self._actTimer = setTimeout(function() {
            _self._actTimerDown();
        }, 1000)
    },

    /**
     * swiper切换时
     */
    _swiperChange: function(evt) {
        this.setData({
            curSwiperIndex: evt.detail.current,
        });
    },

    /**
     * 预览图片
     */
    _previewImg: function(evt) {
        var formId = evt.detail.formId;
        var {
            imageUrls,
            current
        } = evt.target.dataset;

        wx.previewImage({
            current: current || this.data.imageUrls[this.data.curSwiperIndex],
            urls: imageUrls || this.data.imageUrls,
        })
        common.submitForm(formId);
    },

    /**
     * 选择sku
     */
    _selectSku(evt) {
        var {
            groupIndex,
            skuIndex,
            isDisabled,
            isSelected
        } = evt.currentTarget.dataset;
        if (isDisabled) {
            return;
        }
        var skuList = this.data.skuList;
        var groupObj = skuList[groupIndex];

        groupObj.skuArr.some(function(sku, index) {
            if (isSelected) {
                if (skuIndex == index) {
                    sku.selected = false;
                    return true;
                }
            } else {
                sku.selected = index == skuIndex;
                return false;
            }
        });

        this._setNoSelectedSkus(skuList);
        this._setSelectedSkus(skuList);

        this.setData({
            skuList: skuList,
        });

        this._setSkuItem();
        this._resetCounter();
    },

    //处理未选择sku条目
    _setNoSelectedSkus(skuList) {
        var selectedObj = this._getSelectedSkuObj();
        var usableSkuList = this._getUsableSkus(selectedObj);

        skuList.forEach((group) => {
            group.skuArr.forEach(function(skuItem) {
                var uSkus = usableSkuList[group.text];
                skuItem.disabled = uSkus.indexOf(skuItem.text) == -1;
            });
        });

        return skuList;
    },

    //处理已选择sku条目
    _setSelectedSkus(skuList) {
        if (!(skuList && (skuList instanceof Array))) {
            return skuList;
        }
        skuList.forEach((group) => {
            var hasSelected = group.skuArr.some(function(skuItem) {
                if (skuItem.selected) {
                    return true;
                }
            });

            if (!hasSelected) {
                return;
            }
            var selectedObj = this._getSelectedSkuObj(group.text);
            var usableSkuList = this._getUsableSkus(selectedObj);

            group.skuArr.forEach((skuItem) => {
                var uSkus = usableSkuList[group.text];
                skuItem.disabled = uSkus.indexOf(skuItem.text) == -1;
            })
        });
        return skuList;
    },

    /**
     * 获取可用sku项
     * @param  {[type]} skuObj [已选择的sku或假设已选择的sku]
     * @return {[type]}        [description]
     */
    _getUsableSkus(skuObj) {
        var skuJson = this._skuJson;
        var skuObjStr = JSON.stringify(skuObj);
        var usableSkuList = {};

        skuObjStr = skuObjStr.replace(/\{([^\}]*)\}/, '$1')

        skuJson.forEach((skuItem) => {
            var skuValue = skuItem.skuValue;

            if (this._isAllInSkuValue(skuValue, skuObjStr)) {
                var obj = JSON.parse(skuValue);

                Object.keys(obj).forEach((key) => {
                    var group = usableSkuList[key];
                    var skuText = obj[key];

                    if (group) {
                        if (group.indexOf(skuText) == -1) {
                            group.push(skuText);
                        }
                    } else {
                        usableSkuList[key] = [skuText];
                    }
                })
            }
        });
        return usableSkuList;
    },

    _isAllInSkuValue(skuValue, skus) {
        var arr = skus.split(',');

        return arr.every((sku) => {
            return skuValue.indexOf(sku) > -1;
        });
    },

    /**
     * 获取选中sku，指定sku组除外
     * @param  {[type]} exceptSkuRow [description]
     * @return {[type]}              [description]
     */
    _getSelectedSkuObj(exceptSkuRow) {
        var skuList = this.data.skuList;
        var selectedObj = {};

        skuList.forEach(function(group) {
            if (!exceptSkuRow || group.text != exceptSkuRow) {
                group.skuArr.some(function(skuItem) {
                    if (skuItem.selected) {
                        selectedObj[group.text] = skuItem.text;
                        return true;
                    }
                });
            }
        });
        return selectedObj;
    },

    /**
     * 立即购买
     */
    _buy: function(evt) {
        var formId = evt.detail.formId;
        common.submitForm(formId);

        if (this.data.isLogin) {
            this._showPanel(1);
        } else {
            this._showLogin();
        }
    },

    /**
     * 确定下单
     */
    _confirmBuy(evt) {
        var self = this;
        var formId = evt.detail.formId;

        if (!self._validSubmit()) {
            return;
        }
        self._login(function() {
            quickBuy();
        });

        function quickBuy() {
            self.setData({
                dataLoaded: false
            });
            var {
                actId,
                actType,
                groupBuyId,
            } = self.options;
            var ajaxUrl = '/openapi/CHome/showQuickBuy';
            var ajaxParams = {
                goodsId: self.data.goodsId,
                skuId: self.data.curSkuItem.skuId,
                amount: self.data.counter.number,
                act_id: actId,
                act_type: actType,
            };

            ajax.P(ajaxUrl, ajaxParams, function(data) {
                self.setData({
                    dataLoaded: true
                });
                self._closePanel();
                wx.navigateTo({
                    url: '../confirmOrder/confirmOrder?goodsId=' + self.data.goodsId + '&skuId=' + self.data.curSkuItem.skuId + '&amount=' + self.data.counter.number + '&actId=' + actId + '&actType=' + actType + '&groupBuyId=' + groupBuyId
                })
            }, function() {
                self.setData({
                    dataLoaded: true
                });
            });
        }
        common.submitForm(formId);
    },

    /**
     * 加入购物车
     */
    _addCart: function(evt) {
        var formId = evt.detail.formId;

        common.submitForm(formId);

        if (this.data.isLogin) {
            this._showPanel(2);
        } else {
            this._showLogin();
        }
    },

    /**
     * 确定加入购物车
     */
    _confirmAddCart: function(evt) {
        var self = this;
        var formId = evt.detail.formId;
        if (!self._validSubmit()) {
            return;
        }
        self.setData({
            dataLoaded: false
        })
        self._login(function() {
            ajax.P('/openapi/CCart/add', {
                goodsId: self.data.goodsId,
                skuId: self.data.curSkuItem.skuId,
                amount: self.data.counter.number,
            }, function(data) {
                self._closePanel();
                util.showOK('加入购物车成功');

                self._getCartAmount();
            });
        });
        common.submitForm(formId);
    },

    /**
     * 获取购物车数量
     */
    _getCartAmount: function() {
        var self = this;

        if (!self.data.isLogin) {
            return;
        }
        ajax.P('/openapi/CCart/getCartAmount', {}, function(res) {
            self.setData({
                cartAmount: res['result']['number'] || 0
            });
        });
    },

    _validSubmit() {
        var self = this;
        var skuList = self.data.skuList;
        var curSkuItem = self.data.curSkuItem;

        if (!self.data.isLogin && !self.data.panel.phone) {
            util.alert('请输入手机号');
            return false;
        } else if (!self.data.isLogin && !self.data.panel.yzm) {
            util.alert('请输入验证码');
            return false;
        } else if (!curSkuItem) {
            var skuStr = '';

            skuList.forEach((group) => {
                var hasSelected = group.skuArr.some((skuItem) => {
                    return skuItem.selected;
                });
                if (!hasSelected) {
                    skuStr += group.text + ' ';
                }
            })
            util.alert('请选择 ' + skuStr);
            return false;
        } else if (self.data.counter.number > curSkuItem.amount) {
            util.alert('库存不足');
            return false;
        } else if (self.data.counter.number <= 0) {
            util.alert('请输入正确的购买数量哦~');
            return false;
        }
        return true;
    },

    /**
     * 登陆
     */
    _login(cb) {
        var self = this;
        var panel = self.data.panel;

        if (app.getUserSid()) {
            cb && cb();
        } else {
            ajax.P('/openapi/CBrand/bandPhone2', {
                code: panel.yzm,
                phone: panel.phone,
                openId: app.getOpenId(),
            }, function(data) {
                var userSid = data.result.userSid;

                app.setUserSid(userSid);
                self.setData({
                    isLogin: !!userSid
                });
                cb && cb();
            });
        }
    },

    /**
     * 手机号输入
     */
    _phoneInput: function(evt) {
        var panel = this.data.panel;

        panel.phone = evt.detail.value;
        this.setData({
            panel
        });
    },

    /**
     * 验证码输入
     */
    _yzmInput: function(evt) {
        var panel = this.data.panel;

        panel.yzm = evt.detail.value;
        this.setData({
            panel
        });
    },

    /**
     * 获取验证码
     */
    _getYzm(evt) {
        var formId = evt.detail.formId;
        common.submitForm(formId);
        if (!this.data.panel.phone) {
            return util.alert('请输入手机号');
        }
        ajax.P('/openapi/CBrand/sendMsg2', {
            phone: this.data.panel.phone,
        }, function(data) {
            this._timerDown(60);
        }.bind(this));
    },

    /**
     * 倒计时
     */
    _timerDown: function(time) {
        var panel = this.data.panel;

        panel.yzmTime = --time;
        this.setData({
            panel
        });
        if (time == 0) {
            return;
        }
        setTimeout(function() {
            this._timerDown(time);
        }.bind(this), 1000);
    },

    /**
     * 展示购买浮层
     */
    _showPanel(ty) {
        var $this = this;
        var panel = this.data.panel;

        panel.type = ty;
        $this.animation = wx.createAnimation({
            duration: 500,
            timingFunction: "ease-out"
        });
        $this.opacityAnimation = wx.createAnimation({
            duration: 500,
            timingFunction: "ease-out"
        });

        panel.isShow = true;
        $this.setData({
            panel
        });

        setTimeout(function() {
            $this.animation.translateY(0).step();
            $this.opacityAnimation.opacity(1).step();

            panel.animation = $this.animation.export();
            panel.opacityAnimation = $this.opacityAnimation.export();

            $this.setData({
                panel
            });
        }, 0);
    },

    /**
     * 关闭购买浮层
     */
    _closePanel(evt) {
        var $this = this;
        var panel = this.data.panel;
        $this.animation.translateY('100%').step();
        $this.opacityAnimation.opacity(0).step();

        panel.animation = $this.animation.export();
        panel.opacityAnimation = $this.opacityAnimation.export();

        $this.setData({
            panel,
            dataLoaded: true
        })
        setTimeout(function() {
            panel.isShow = false;
            $this.setData({
                panel
            });
        }, 500)
        if (evt) {
            var formId = evt.detail.formId;
            common.submitForm(formId);
        }

    },

    /**
     * sku变化时，重围计数器
     */
    _resetCounter() {
        var curSkuItem = this.data.curSkuItem;
        if (!curSkuItem) {
            return;
        }
        var amount = +curSkuItem.amount; //当前库存
        var counter = this.data.counter;

        if (counter.number > amount) {
            counter.number = amount;
        }

        counter.minusDisabled = counter.number <= 0;
        counter.addDisabled = counter.number >= amount;
        this.setData({
            counter
        });
    },

    /**
     * 计数器+
     */
    _add: function(evt) {
        var counter = this.data.counter;
        var formId = evt.detail.formId;
        var max = evt.currentTarget.dataset.max;

        if (max != undefined && ++counter.number > max) {
            counter.number = max;
        }
        if (counter.number == max && max == 0) {
            counter.addDisabled = true;
        } else if (counter.number == max && max != 0) {
            counter.addDisabled = true;
        } else {
            counter.minusDisabled = false;
        }
        this.setData({
            counter,
        });
        common.submitForm(formId);
    },

    /**
     * 计数器-
     */
    _minus: function(evt) {
        var counter = this.data.counter;
        var formId = evt.detail.formId;
        var min = evt.currentTarget.dataset.min;

        if (min != undefined && --counter.number < min) {
            counter.number = min;
        }
        if (counter.number < 0) {
            counter.number = 0;
        }
        if (counter.number == min) {
            counter.minusDisabled = true;
        } else {
            counter.addDisabled = false;
        }

        this.setData({
            counter
        });
        common.submitForm(formId);
    },

    /**
     * 计数量input输入
     */
    _changeNum: function(evt) {
        var val = parseInt(evt.detail.value) || 1;
        var counter = this.data.counter;

        counter.number = val;
        this.setData(counter);
    },

    /**
     * 根据窗口大小，初始化组件宽高
     */
    _initSizeByWin: function() {
        var $this = this;
        // var panel = this.data.panel;

        wx.getSystemInfo({
            success: function(res) {
                // panel.height = res.windowHeight * 0.85;
                $this.setData({
                    swiperHei: res.windowWidth * 0.53,
                    // panel
                });
            }
        })
    },

    /**
     * 重组sku列表数据结构
     */
    _setSkuList() {
        var goodsSku = this._goodsSku;
        var skuList = this.data.skuList;

        Object.keys(goodsSku).forEach(function(key) {
            var skuArr = goodsSku[key];
            var skuItem = {
                text: key,
                skuArr: [],
            }

            skuArr.forEach(function(text, index) {
                skuItem.skuArr.push({
                    text: text,
                    // selected: index == 0 ? true : false
                    selected: false
                })
            });
            skuList.push(skuItem)
        });

        this.setData({
            skuList: skuList
        });
    },

    /**
     * 设置当前选中sku
     */
    _setSkuItem() {
        var skuList = this.data.skuList;
        var skuJson = this._skuJson;
        var curSkuItem = null;
        var selectedObj = {};

        skuList.forEach(function(group) {
            group.skuArr.some(function(skuItem) {
                if (skuItem.selected) {
                    selectedObj[group.text] = skuItem.text;
                    return true;
                }
            });
        });

        skuJson.some(function(sku) {
            if (sku.skuValue == JSON.stringify(selectedObj)) {
                curSkuItem = {
                    skuId: sku.skuId,
                    price: sku.price,
                    amount: sku.amount,
                };
                return true;
            }
        });
        this.setData({
            curSkuItem: curSkuItem,
        });
    },

    //收藏
    _collect(evt) {
        var _self = this;
        var formId = evt.detail.formId;

        ajax.P('/openapi/CUser/doCollect', {
            id: this.data.goodsId,
            type: 0
        }, function(data) {
            _self.setData({
                isCollected: true,
                collectId: data.result.id
            });
            util.showOK('收藏成功');

        }, (data) => {
            if (data.code == 107) {
                this._showLogin();
            } else {
                data.msg && util.alert(data.msg);
            }
        }, true);
        common.submitForm(formId);
    },

    //取消收藏
    _delCollect(evt) {
        var _self = this;
        var collectId = _self.data.collectId;
        var formId = evt.detail.formId;

        ajax.P('/openapi/CUser/delCollections', {
            idStr: collectId + ''
        }, function(data) {

            _self.setData({
                isCollected: false
            });
            util.showOK('已取消收藏');

        }, (data) => {
            if (data.code == 107) {
                this._showLogin();
            } else {
                data.msg && util.alert(data.msg);
            }
        }, true);
        common.submitForm(formId);
    },
    _jump: function(evt) {
        common.jump(evt);
    },

    //评论列表
    _getCommentList(page = 1) {
        if (page > 1) {
            this.setData({
                commentsLoading: true
            });
        }
        ajax.G('/openapi/CGoods/moreComment', {
            type: 0,
            page,
            goodsId: this.data.goodsId
        }, (data) => {
            var list = data.result.commentlist.data || [];
            var totalNum = data.result.commentlist.total_num;
            var allList = this.data.commentlist;

            allList = allList.concat(list);

            this.setData({
                commentlist: allList,
                commentsPageOver: list.length < 5,
                commentsLoading: false,
                commentTotal: totalNum,
            })
        });
    },

    //加载更多评论
    _loadMoreComments() {
        var {
            commentsPageOver
        } = this.data;

        if (commentsPageOver) {
            return;
        }
        if (!this._commentsPage) {
            this._commentsPage = 1;
        }
        this._getCommentList(++this._commentsPage);
    },

    //点赞头像列表
    _getLikeList() {
        ajax.G('/openapi/CGoods/likeInfo', {
            goodsId: this.data.goodsId
        }, (data) => {
            var {
                supportList,
                isSupport,
                supportTotal
            } = data.result;

            this.setData({
                isSupport,
                supportList,
                supportTotal
            })
        });
    },

    //点赞
    _likeGoods() {
        if (this.data.isSupport == 1) {
            return;
        }
        ajax.P('/openapi/CGoods/likeGoods', {
            goodsId: this.data.goodsId
        }, (data) => {
            var {
                supportList = [],
                    supportTotal
            } = this.data;

            supportList.push({
                headImg: data.result.headImg
            })

            this.setData({
                supportList,
                supportTotal: ++supportTotal,
                isSupport: 1
            })
        }, (data) => {
            if (data.code == 107) {
                this._showLogin();
            } else {
                data.msg && util.alert(data.msg);
            }
        }, true);
    },

    //给评论点赞
    _likeComment(e) {
        var {
            commentId,
            isSupport
        } = e.currentTarget.dataset;

        if (isSupport == 1) {
            return;
        }
        ajax.P('/openapi/CGoods/likeComment', {
            commentId
        }, (data) => {
            var {
                commentlist
            } = this.data;

            commentlist.some((comment) => {
                if (comment.id == commentId) {
                    comment.isSupport = 1;
                    comment.comment_praise_num = parseInt(comment.comment_praise_num) + 1;
                    return true;
                }
            })
            this.setData({
                commentlist
            })
        }, (data) => {
            if (data.code == 107) {
                this._showLogin();
            } else {
                data.msg && util.alert(data.msg);
            }
        }, true);
    }


}));